package com.xyht.sca_s.student_manage_system.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.entity.req.RoleUserReq;
import com.xyht.sca_s.student_manage_system.modules.user.entity.req.SmsRoleReq;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsRoleResp;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsSearchUserResp;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.service.SmsRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.RoleCanDeletedFlag.CAN_NOT_DELETED;

/**
 * <p>
 * 角色信息 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-11-29
 */
@Service
public class SmsRoleServiceImpl extends ServiceImpl<SmsRoleMapper, SmsRole> implements SmsRoleService {
    @Resource
    private SmsRoleMapper smsRoleMapper;
    @Resource
    private SmsUserRoleRelationMapper smsUserRoleRelationMapper;
    @Resource
    private SmsUserMapper smsUserMapper;

    @Override
    public ResponseResult addRole(SmsRoleReq smsRoleReq) {
        if (isNullOrEmpty(smsRoleReq.getRoleName())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<SmsRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsRole::getRoleName, smsRoleReq.getRoleName());
        SmsRole smsRole = smsRoleMapper.selectOne(queryWrapper);
        if (smsRole != null) {
            return CommonResult.failed(CommonCodeEnum.ROLE_NAME_EXIST);
        }
        SmsRole smsRole1 = new SmsRole();
        BeanUtils.copyProperties(smsRoleReq, smsRole1);
        smsRoleMapper.insert(smsRole1);
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateRole(SmsRoleReq smsRoleReq) {
        if (isNullOrEmpty(smsRoleReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRole smsRole = smsRoleMapper.selectById(smsRoleReq.getId());
        if (smsRole == null) {
            return CommonResult.failed(CommonCodeEnum.ROLE_NOT_EXIST);
        }
        if (smsRole.getCanDeleted() == CAN_NOT_DELETED) {
            return CommonResult.failed(CommonCodeEnum.ROLE_CAN_NOT_DELETE);
        }
        if (!smsRole.getRoleName().equals(smsRoleReq.getRoleName())) {
            QueryWrapper<SmsRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SmsRole::getRoleName, smsRoleReq.getRoleName());
            SmsRole smsRole1 = smsRoleMapper.selectOne(queryWrapper);
            if (smsRole1 != null) {
                return CommonResult.failed(CommonCodeEnum.ROLE_NAME_EXIST);
            }
        }

        SmsRole updateRole = new SmsRole();
        BeanUtils.copyProperties(smsRoleReq, updateRole);
        smsRoleMapper.updateById(updateRole);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getRoleList(Integer pageSize, Integer pageNum) {
        Page<SmsRole> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(SmsRole::getCreateTime);
        smsRoleMapper.selectPage(page, queryWrapper);
        List<SmsRole> roleList = page.getRecords();
        List<SmsRoleResp> roleRespList = roleList.stream().map(item -> {
            SmsRoleResp smsRoleResp = new SmsRoleResp();
            BeanUtils.copyProperties(item, smsRoleResp);
            return smsRoleResp;
        }).collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(roleRespList, total);
    }

    @Override
    public ResponseResult getRoleByID(String role_id) {
        if (isNullOrEmpty(role_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRole smsRole = smsRoleMapper.selectById(role_id);
        if (smsRole == null) {
            return CommonResult.failed(CommonCodeEnum.ROLE_NOT_EXIST);
        }
        return CommonResult.success(smsRole);
    }

    @Override
    public ResponseResult deleteRole(String role_id) {
        if (isNullOrEmpty(role_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRole smsRole = smsRoleMapper.selectById(role_id);
        if (smsRole == null) {
            return CommonResult.failed(CommonCodeEnum.ROLE_NOT_EXIST);
        }
        if (smsRole.getCanDeleted().equals(CAN_NOT_DELETED)) {
            return CommonResult.failed(CommonCodeEnum.ROLE_CAN_NOT_DELETE);
        }

        smsRoleMapper.deleteById(role_id);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getRoleUserList(String role_id, Integer pageNum, Integer pageSize) {
        QueryWrapper<SmsUserRoleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsUserRoleRelation::getRoleId, role_id);

        Page<SmsUserRoleRelation> page = new Page<>(pageNum, pageSize);
        smsUserRoleRelationMapper.selectPage(page, queryWrapper);

        List<SmsSearchUserResp> userList = page.getRecords()
                .stream()
                .map(relation -> {
                    SmsSearchUserResp smsSearchUserResp = new SmsSearchUserResp();

                    SmsUser smsUser = smsUserMapper.selectById(relation.getUserId());
                    if (smsUser != null) {
                        BeanUtils.copyProperties(smsUser, smsSearchUserResp);
                    }
                    return smsSearchUserResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(userList,total);
    }

    @Override
    public ResponseResult addRoleUser(RoleUserReq roleUserReq) {
        if (isNullOrEmpty(roleUserReq.getUserList(),roleUserReq.getRoleId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (roleUserReq.getUserList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsRole smsRole = smsRoleMapper.selectById(roleUserReq.getRoleId());
        if (smsRole == null){
            return CommonResult.failed(CommonCodeEnum.ROLE_NOT_EXIST);
        }

        for (String user_id: roleUserReq.getUserList()) {
            List<SmsUserRoleRelation> list = smsUserRoleRelationMapper.selectList(new LambdaQueryWrapper<SmsUserRoleRelation>()
                    .eq(SmsUserRoleRelation::getRoleId,roleUserReq.getRoleId())
                    .eq(SmsUserRoleRelation::getUserId,user_id));
            if (list!=null && list.size()>0){
                continue;
            }
            SmsUserRoleRelation addRelation = new SmsUserRoleRelation();
            addRelation.setUserId(user_id);
            addRelation.setRoleId(roleUserReq.getRoleId());
            smsUserRoleRelationMapper.insert(addRelation);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult deleteRoleUser(RoleUserReq roleUserReq) {
        if (isNullOrEmpty(roleUserReq.getUserList(),roleUserReq.getRoleId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (roleUserReq.getUserList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        for (String user_id: roleUserReq.getUserList()) {
            smsUserRoleRelationMapper.delete(new LambdaQueryWrapper<SmsUserRoleRelation>()
                    .eq(SmsUserRoleRelation::getRoleId,roleUserReq.getRoleId())
                    .eq(SmsUserRoleRelation::getUserId,user_id));
        }
        return CommonResult.success();
    }
}
